import React, { useState, useEffect, useRef, useCallback } from 'react';
import './SubtitleDisplay.css';
import aiService from '../utils/aiService';
import AIAnalysis from './AIAnalysis';

const SubtitleDisplay = ({ 
  subtitles, 
  currentTime, 
  onSubtitleClick, 
  onRepeatSet, 
  showTranslation = false, 
  onTranslationToggle,
  aiEnabled = false 
}) => {
  const [activeIndex, setActiveIndex] = useState(-1);
  const [isUserScrolling, setIsUserScrolling] = useState(false);
  const [autoScroll, setAutoScroll] = useState(true);
  const [showGoToCurrent, setShowGoToCurrent] = useState(false);
  
  // AI功能相关状态
  const [showAnalysis, setShowAnalysis] = useState(false);
  const [currentAnalysis, setCurrentAnalysis] = useState(null);
  const [analyzingSubtitle, setAnalyzingSubtitle] = useState(null);
  const [analyzedSubtitle, setAnalyzedSubtitle] = useState(null); // 保存已分析的字幕对象
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  
  const containerRef = useRef(null);
  const subtitleRefs = useRef([]);
  const scrollTimeoutRef = useRef(null);
  const lastScrollTopRef = useRef(0);

  // 检测用户滚动
  const handleScroll = useCallback(() => {
    const container = containerRef.current;
    if (!container) return;

    const currentScrollTop = container.scrollTop;
    
    // 检测是否是用户主动滚动（而非程序滚动）
    if (Math.abs(currentScrollTop - lastScrollTopRef.current) > 5) {
      setIsUserScrolling(true);
      setShowGoToCurrent(true);
      
      // 清除之前的定时器
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
      
      // 3秒后恢复自动滚动
      scrollTimeoutRef.current = setTimeout(() => {
        setIsUserScrolling(false);
        setShowGoToCurrent(false);
      }, 3000);
    }
    
    lastScrollTopRef.current = currentScrollTop;
  }, []);

  // 滚动到当前播放位置
  const scrollToCurrentSubtitle = useCallback(() => {
    if (activeIndex >= 0 && subtitleRefs.current[activeIndex]) {
      subtitleRefs.current[activeIndex].scrollIntoView({
        behavior: 'smooth',
        block: 'center'
      });
      setIsUserScrolling(false);
      setShowGoToCurrent(false);
    }
  }, [activeIndex]);

  // 切换自动滚动
  const toggleAutoScroll = () => {
    setAutoScroll(!autoScroll);
    if (!autoScroll && activeIndex >= 0) {
      // 如果刚开启自动滚动，立即滚动到当前位置
      scrollToCurrentSubtitle();
    }
  };

  useEffect(() => {
    if (!subtitles || subtitles.length === 0) return;

    let newActiveIndex = -1;
    
    for (let i = 0; i < subtitles.length; i++) {
      const subtitle = subtitles[i];
      if (currentTime >= subtitle.start && currentTime <= subtitle.end) {
        newActiveIndex = i;
        break;
      }
    }

    if (newActiveIndex !== activeIndex) {
      setActiveIndex(newActiveIndex);
      
      // 只在用户未手动滚动且开启自动滚动时才自动滚动
      if (!isUserScrolling && autoScroll && newActiveIndex >= 0 && subtitleRefs.current[newActiveIndex]) {
        lastScrollTopRef.current = containerRef.current?.scrollTop || 0;
        subtitleRefs.current[newActiveIndex].scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        });
      }
    }
  }, [currentTime, subtitles, activeIndex, isUserScrolling, autoScroll]);

  // 添加滚动事件监听器
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    container.addEventListener('scroll', handleScroll, { passive: true });
    
    return () => {
      container.removeEventListener('scroll', handleScroll);
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
    };
  }, [handleScroll]);

  const handleSubtitleClick = (subtitle, index) => {
    if (onSubtitleClick) {
      onSubtitleClick(subtitle.start);
    }
  };

  const handleSubtitleDoubleClick = (subtitle, index) => {
    if (onRepeatSet) {
      onRepeatSet(subtitle.start, subtitle.end);
    }
  };

  // AI分析字幕
  const handleAnalyzeSubtitle = async (subtitle, forceRefresh = false) => {
    if (!aiEnabled || !aiService.isEnabled()) {
      return;
    }

    setAnalyzingSubtitle(subtitle);
    setIsAnalyzing(true);

    try {
      const result = await aiService.analyzeSubtitle(subtitle, forceRefresh);
      setCurrentAnalysis(result.analysis);
      setAnalyzedSubtitle(subtitle); // 保存字幕对象供分析窗口使用
      setShowAnalysis(true);
    } catch (error) {
      console.error('AI analysis failed:', error);
      alert('AI分析失败：' + error.message);
    } finally {
      setIsAnalyzing(false);
      setAnalyzingSubtitle(null);
    }
  };

  // 重新分析（强制刷新）
  const handleRefreshAnalysis = async () => {
    if (analyzedSubtitle) {
      await handleAnalyzeSubtitle(analyzedSubtitle, true);
    }
  };

  // 处理词汇点击
  const handleWordClick = async (word) => {
    if (!aiEnabled || !aiService.isEnabled()) {
      return;
    }

    try {
      const result = await aiService.explainWord(word, analyzedSubtitle?.text);
      // 这里可以显示词汇解释弹窗，暂时打印到控制台
      console.log('Word explanation:', result);
    } catch (error) {
      console.error('Word explanation failed:', error);
    }
  };

  const formatTime = (time) => {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    const milliseconds = Math.floor((time % 1) * 100);
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(2, '0')}`;
  };

  if (!subtitles || subtitles.length === 0) {
    return (
      <div className="subtitle-display">
        <div className="no-subtitles">
          <p>暂无字幕文件</p>
          <p className="hint">请导入包含字幕文件(.srt)的文件夹</p>
        </div>
      </div>
    );
  }

  return (
    <div className="subtitle-display">
      <div className="subtitle-help">
        <div className="help-text">
          <p>💡 点击字幕跳转播放，双击设置重复范围</p>
        </div>
        <div className="subtitle-controls">
          {aiEnabled && (
            <button 
              className={`translation-btn ${showTranslation ? 'active' : ''}`}
              onClick={onTranslationToggle}
              title={showTranslation ? '隐藏翻译' : '显示翻译'}
            >
              {showTranslation ? '译' : '原'}
            </button>
          )}
          <button 
            className={`auto-scroll-btn ${autoScroll ? 'active' : ''}`}
            onClick={toggleAutoScroll}
            title={autoScroll ? '关闭自动滚动' : '开启自动滚动'}
          >
            {autoScroll ? '🔒' : '🔓'}
          </button>
        </div>
      </div>
      
      <div className="subtitle-list" ref={containerRef}>
        {subtitles.map((subtitle, index) => (
          <div
            key={index}
            ref={el => subtitleRefs.current[index] = el}
            className={`subtitle-item ${index === activeIndex ? 'active' : ''}`}
            onClick={() => handleSubtitleClick(subtitle, index)}
            onDoubleClick={() => handleSubtitleDoubleClick(subtitle, index)}
          >
            <div className="subtitle-header">
              <div className="subtitle-time">
                {formatTime(subtitle.start)} - {formatTime(subtitle.end)}
              </div>
              {aiEnabled && (
                <div className="subtitle-actions">
                  <button
                    className="analyze-btn"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleAnalyzeSubtitle(subtitle);
                    }}
                    disabled={isAnalyzing}
                    title="AI智能解析"
                  >
                    {isAnalyzing && analyzingSubtitle === subtitle ? '⏳' : '🎓'}
                  </button>
                </div>
              )}
            </div>
            <div className="subtitle-text">
              {subtitle.text}
            </div>
            {showTranslation && subtitle.translation && (
              <div className="subtitle-translation">
                {subtitle.translation}
              </div>
            )}
          </div>
        ))}
      </div>

      {/* 浮动的回到当前位置按钮 */}
      {showGoToCurrent && (
        <button 
          className="go-to-current-btn"
          onClick={scrollToCurrentSubtitle}
          title="回到当前播放位置"
        >
          🎯
        </button>
      )}

      {/* 用户滚动提示 */}
      {isUserScrolling && (
        <div className="scroll-status">
          <span>已暂停自动滚动 (3秒后恢复)</span>
        </div>
      )}

      {/* AI分析弹窗 */}
      {showAnalysis && currentAnalysis && analyzedSubtitle && (
        <AIAnalysis
          isVisible={showAnalysis}
          subtitle={analyzedSubtitle}
          analysis={currentAnalysis}
          isAnalyzing={isAnalyzing}
          onClose={() => {
            setShowAnalysis(false);
            setCurrentAnalysis(null);
            setAnalyzedSubtitle(null);
          }}
          onRefresh={handleRefreshAnalysis}
          onWordClick={handleWordClick}
        />
      )}
    </div>
  );
};

export default SubtitleDisplay;